package com.hy.util;

import com.hy.entity.User;
import com.hy.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * 用户工具类
 */
@Component
public class UserUtil {

    @Autowired
    private JwtUtil jwtUtil;
    
    @Autowired
    private UserService userService;

    /**
     * 获取当前登录用户ID
     */
    public Integer getCurrentUserId() {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        return (Integer) request.getAttribute("userId");
    }

    /**
     * 获取当前登录用户信息
     */
    public User getCurrentUser() {
        Integer userId = getCurrentUserId();
        return userService.getById(userId);
    }

    /**
     * 从请求头中获取token
     */
    public String getToken() {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String token = request.getHeader("Authorization");
        if (token != null && token.startsWith("Bearer ")) {
            return token.substring(7);
        }
        return null;
    }

    /**
     * 从token中获取用户ID
     */
    public Integer getUserIdFromToken() {
        String token = getToken();
        if (token != null) {
            return jwtUtil.getUserIdFromToken(token);
        }
        return null;
    }

    /**
     * 从token中获取openid
     */
    public String getOpenidFromToken() {
        String token = getToken();
        if (token != null) {
            return jwtUtil.getOpenidFromToken(token);
        }
        return null;
    }

    /**
     * 验证token是否有效
     */
    public boolean validateToken() {
        String token = getToken();
        return token != null && jwtUtil.validateToken(token);
    }
} 